package com.jinbooks.autoconfigure;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jinbooks.crypto.password.PasswordReciprocal;
import com.jinbooks.entity.SocialsProvider;
import com.jinbooks.persistence.service.SocialsProviderService;
import com.jinbooks.web.oauth2.social.properties.SocialLoginConfigProperties;
import com.jinbooks.web.oauth2.social.properties.SocialProperties;
import com.jinbooks.web.oauth2.social.utils.AuthRedisStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Social 配置属性
 *
 * @author thiszhc
 */
@AutoConfiguration
public class SocialConfig {

    @Autowired
    private SocialsProviderService socialsProviderService;

    // 使用线程安全的Map存储社交登录配置缓存
    private final Map<String, SocialLoginConfigProperties> configCache = new ConcurrentHashMap<>();
    
    // 缓存更新时间
    private volatile long lastUpdate = 0;
    
    // 缓存过期时间(毫秒)，默认5分钟
    private static final long CACHE_EXPIRE_TIME = 5 * 60 * 1000;
    
    // SocialProperties实例
    private SocialProperties socialProperties;

    @Bean
    public SocialProperties socialProperties() {
        socialProperties = new SocialProperties();
        // 确保type属性被初始化
        socialProperties.setType(new HashMap<>());
        
        // 初始化时加载配置
        refreshConfigCache();
        
        // 使用缓存的配置
        socialProperties.setType(configCache);
        return socialProperties;
    }

    @Bean
    public AuthStateCache authStateCache() {
        return new AuthRedisStateCache();
    }
    
    /**
     * 刷新配置缓存
     */
    public void refreshConfigCache() {
        // 从数据库加载所有启用的社交登录配置
        Map<String, SocialLoginConfigProperties> typeMap = new HashMap<>();

        // 获取所有启用的社交登录提供商
        LambdaQueryWrapper<SocialsProvider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SocialsProvider::getStatus, 1);
        List<SocialsProvider> providers = socialsProviderService.list(queryWrapper);

        // 转换为SocialLoginConfigProperties
        for (SocialsProvider provider : providers) {
            SocialLoginConfigProperties config = new SocialLoginConfigProperties();
            config.setClientId(provider.getClientId());
            config.setClientSecret(PasswordReciprocal.getInstance().decoder(provider.getClientSecret()));
            config.setRedirectUri(provider.getRedirectUri());
            config.setAgentId(provider.getAgentId());
            config.setServerUrl(provider.getAuthorizationUri());

            // 特定平台属性设置 todo

            typeMap.put(provider.getProvider(), config);
        }
        
        // 更新缓存
        configCache.clear();
        configCache.putAll(typeMap);
        lastUpdate = System.currentTimeMillis();
        
        // 同时更新SocialProperties中的配置（确保type不为null）
        if (socialProperties != null) {
            if (socialProperties.getType() == null) {
                socialProperties.setType(new HashMap<>());
            }
            socialProperties.getType().clear();
            socialProperties.getType().putAll(typeMap);
        }
    }
    
    /**
     * 获取指定source的社交登录配置，如果缓存过期则刷新缓存
     * 
     * @param source 社交登录来源
     * @return 社交登录配置
     */
    public SocialLoginConfigProperties getSocialLoginConfig(String source) {
        // 检查缓存是否过期
        if (System.currentTimeMillis() - lastUpdate > CACHE_EXPIRE_TIME) {
            refreshConfigCache();
        }
        
        return configCache.get(source);
    }
    
    /**
     * 手动刷新缓存的方法
     */
    public void forceRefreshConfigCache() {
        refreshConfigCache();
    }
    
    /**
     * 清除缓存，下次访问时会重新加载
     */
    public void clearCache() {
        lastUpdate = 0;
    }
}